﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OAuthProtocol;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using Microsoft.Web.WebPages.OAuth;
using System.Web.Routing;
using WebMatrix.WebData;
using System.Collections.Generic;

using Dropbox.Api;
using CloudTree.Models;
using CloudTree.Filters;

namespace CloudTree.Controllers
{
     [InitializeSimpleMembership]
    public class LinkController : Controller
    {
        private const string ConsumerKey = "07hhp48nehsni1u";
        private const string ConsumerSecret = "fqzqelyk8f8ikd9";

         /*
        public ActionResult CheckForToken()
        {
            int userID = WebSecurity.CurrentUserId;

            if (User.Identity.IsAuthenticated)//If the user is logged in
            {
                using (UsersContext db = new UsersContext())
                {
                   var token = (from p in db.UserProfiles
                               where p.UserId == userID
                               select p).FirstOrDefault();
                    if (token == null)
                    {
                        ViewBag.token = token.DrBxToken;
                        return View();
                    }
                    else
                    {
                        return RedirectToAction("Authorized", new { oauth_token = token.DrBxToken });
                    }
                }
            }
            else
            {
                return View();
            }
        }
          */

        public ActionResult AuthorizeDropbox()
        {
            var oAuth = new OAuth();
            var requestToken = oAuth.GetRequestToken (
                new Uri(DropboxRestApi.BaseUri), ConsumerKey, ConsumerSecret);
            Session["requestToken"] = requestToken;//Retreive requestToken and store it, temporerily in the session state

            var action = Url.Action("Authorized", "Link", null, Request.Url.Scheme);
            var callbackUri = new Uri(action);//Composes the callback uri which is called after the user has authorised CloudTree

            var authorizeUri = oAuth.GetAuthorizeUri(
                new Uri(DropboxRestApi.AuthorizeBaseUri), requestToken, callbackUri);//Retreive authorised uri

            return Redirect(authorizeUri.ToString());//Redirect the user to the Authorized page 
        }

        //Action to handle the callback generated from AuthorizeDropbox
       
        public ActionResult Authorized(string oauth_token)
        {
            
            var requestToken = (OAuthToken)Session["RequestToken"];//Retreive the request token / secret from the sesssion state - this allows us to retreive the access token
            var oAuth = new OAuth();
            var accessToken = oAuth.GetAccessToken(new Uri(DropboxRestApi.BaseUri), ConsumerKey, ConsumerSecret, requestToken);
            setAccessToken(accessToken);
            return View();
        }

        void setAccessToken(OAuthToken AccessToken)
        {
            int userID = WebSecurity.CurrentUserId;

            using (UsersContext db = new UsersContext())
            {
                // Query the database for the row to be updated.
                UserProfile token =
                    (from t in db.UserProfiles
                     where t.UserId == userID
                     select t).FirstOrDefault();
                token.DrBxToken = AccessToken.Token;
                token.DrBxSecret = AccessToken.Secret;

                db.SaveChanges();//Commit the changes to the database
            }
        }

        DataTable GetDataFromQuery(string query)
        {
            SqlConnection connectionString = new SqlConnection("Server=tcp:prmh7s2jpg.database.windows.net,1433;Database=cloudtree;User ID=x00074953@prmh7s2jpg;Password=db30Apr91;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;");
            SqlDataAdapter adap = new SqlDataAdapter(query, connectionString);
            DataTable data = new DataTable();
            adap.Fill(data);
            return data;
        }

    }
}
